//
//  BCScanController.m
//  CloudBusiness
//
//  Created by 王云 on 2017/6/7.
//  Copyright © 2017年 WY. All rights reserved.
//

#import "SCScanController.h"
#import <AVFoundation/AVFoundation.h>
#import  <AVFoundation/AVCaptureDevice.h>
#import "VerResultController.h"
#import "SCLoginController.h"
#import "HomeController.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

@interface SCScanController ()<AVCaptureMetadataOutputObjectsDelegate>

@property (strong , nonatomic) AVCaptureDevice * device;
@property (strong , nonatomic) AVCaptureDeviceInput * input;
@property (strong , nonatomic) AVCaptureMetadataOutput * output;
@property (strong , nonatomic) AVCaptureSession * session;
@property (strong , nonatomic) AVCaptureVideoPreviewLayer * preview;
@property (strong , nonatomic) UIImageView  *qrView;
@property (strong , nonatomic) UIImageView *lineLabel;
@property (strong , nonatomic) NSTimer *lineTimer;
@property (strong , nonatomic) UIView *otherPlatformLoginView;
@property (nonatomic,assign)NSInteger off;

@end
/**
 *  条形码扫描不出来 是 _output setRectOfInterest 问题
 此界面 有内存不销毁问题    
 */
@implementation SCScanController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"扫一扫";
   
    [self setUI];
}

- (void)setUI{
    
    
    UIImageView *bgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, KHeight-100-64)];
    bgV.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bgV];
    
    //扫描区域宽、高大小
    float Qwidth = 200/320.0*kScreenWidth;
    
    //创建扫描区域框
    _qrView=[[UIImageView alloc]initWithFrame:CGRectMake((kWidth-Qwidth)/2, (KHeight-100-64-Qwidth)/2, Qwidth, Qwidth)];
    _qrView.image = [UIImage imageNamed:@"QRImage.png"];
    [bgV addSubview:_qrView];
    
    _lineLabel = [[UIImageView alloc]init];
    _lineLabel.image = [UIImage imageNamed:@"QRLine.png"];
    [bgV addSubview:_lineLabel];
    
    //    //半透明背景
    UIView *qrBacView = [[UIView alloc]init];//上
    qrBacView.backgroundColor = [UIColor blackColor];
    qrBacView.alpha = 0.6;
    [bgV addSubview:qrBacView];
    
    UILabel *titleL = [[UILabel alloc] init];
    titleL.text = @"将取景框对准二维码即可自动扫描";
    [titleL setTextAlignment:NSTextAlignmentCenter];
    titleL.textColor = [UIColor whiteColor];
    titleL.font = [UIFont systemFontOfSize:12];
    titleL.numberOfLines = 2;
    [qrBacView addSubview:titleL];
    
    UIView *qrLView = [[UIView alloc]init];//左
    qrLView.backgroundColor = [UIColor blackColor];
    qrLView.alpha = 0.6;
    [bgV addSubview:qrLView];
    
    UIView *qrBView = [[UIView alloc]init];//下
    qrBView.backgroundColor = [UIColor blackColor];
    qrBView.alpha = 0.6;
    [bgV addSubview:qrBView];

    UIView *qrRView = [[UIView alloc]init];//右
    qrRView.backgroundColor = [UIColor blackColor];
    qrRView.alpha = 0.6;
    [bgV addSubview:qrRView];

    UIView *openV = [[UIView alloc] init];
    openV.backgroundColor = [UIColor blackColor];
    [self.view addSubview:openV];
  
    
    //手电筒开关
    UIButton *OpenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [OpenBtn setImage:[UIImage imageNamed:@"Scan_on"] forState:UIControlStateNormal];
    [OpenBtn setImage:[UIImage imageNamed:@"Scan_off"] forState:UIControlStateSelected];

    [OpenBtn addTarget:self action:@selector(openOrClose:) forControlEvents:UIControlEventTouchUpInside];
    [openV addSubview:OpenBtn];
    
//    UIButton *CodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [CodeBtn setImage:[UIImage imageNamed:@"Scan_code"] forState:UIControlStateNormal];
//    [CodeBtn addTarget:self action:@selector(code) forControlEvents:UIControlEventTouchUpInside];
//    [openV addSubview:CodeBtn];


    
    __weak __typeof(&*self)weakSelf = self;
//    [bgV mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.top.equalTo(weakSelf.view);
//        make.bottom.equalTo(weakSelf.view.mas_bottom).offset(-100);
//    }];
//    [_qrView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.size.mas_equalTo(Qwidth);
//        make.center.mas_equalTo(bgV);
//    }];
    [_lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.qrView.mas_left).offset(2);
        make.top.equalTo(weakSelf.qrView.mas_top).offset(2);
        make.size.mas_equalTo(CGSizeMake(Qwidth-4, 3));
    }];
    [qrBacView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(bgV);
        make.bottom.equalTo(weakSelf.qrView.mas_top);
    }];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(qrBacView);
        make.size.mas_equalTo(CGSizeMake(100, 40));
    }];
    [qrLView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.equalTo(bgV);
        make.top.equalTo(qrBacView.mas_bottom);
        make.right.equalTo(weakSelf.qrView.mas_left);
    }];
    [qrBView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(qrLView.mas_right);
        make.top.equalTo(weakSelf.qrView.mas_bottom);
        make.bottom.right.equalTo(bgV);
    }];
    [qrRView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(qrBacView.mas_bottom);
        make.left.equalTo(weakSelf.qrView.mas_right);
        make.right.equalTo(bgV.mas_right);
        make.bottom.equalTo(qrBView.mas_top);
    }];
    
    [openV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgV.mas_bottom);
        make.left.right.bottom.equalTo(weakSelf.view);
    }];
    [OpenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(openV);
        make.size.mas_equalTo(CGSizeMake(40, 60));
//        make.left.equalTo(openV.mas_left).offset((kWidth/2-40)/2);
        
    }];
//    [CodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.mas_equalTo(openV);
//        make.size.mas_equalTo(CGSizeMake(60, 60));
//        make.right.equalTo(openV.mas_right).offset(-(kWidth/2-60)/2);
//    }];
    
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  
    if(authStatus == AVAuthorizationStatusAuthorized){
        
        [self createQRView];

    }else{
        
//        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
//            if (!granted) {
//                dispatch_async(dispatch_get_main_queue(), ^{
                    [SCTool showAlerts:@"需要您的相机权限" Ok:^(id alerts) {
                        [SCTool showSetting];
                    } Cancel:^(id alerts) {
                         [weakSelf.navigationController popViewControllerAnimated:YES];
                    }];
//                });
//
//            }else{
//                [self createQRView];
//            }
//        }];
    }
}
- (void)createQRView{
    
    float Qwidth = 200/320.0*kScreenWidth;
    
    // 获取 AVCaptureDevice 实例
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 初始化输入流
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    // 初始化输出流
    _output = [[AVCaptureMetadataOutput alloc] init];
    [ _output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue ()];
    //  创建会话
    _session = [[AVCaptureSession alloc] init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    // 添加输入输出流
    if ([_session canAddInput:self.input]){
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output]){
        [_session addOutput:self.output];
    }

    
    

    
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
   
    //设置扫描有效区域(上、左、下、右)
     //这里要记住rectOfInterest这个方法设置的区域是相对于设备的大小的，默认值是CGRectMake(0, 0, 1, 1)，是有比例关系的
    [_output setRectOfInterest : CGRectMake (( _qrView.frame.origin.y )/ kScreenHeight ,(_qrView.frame.origin.x)/ kScreenWidth , Qwidth / kScreenHeight , Qwidth / kScreenWidth )];

    _preview = [ AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill ;
    _preview.frame = self.view.layer.bounds ;
    [self.view.layer insertSublayer:_preview atIndex:0];
    // Start
     
    
    [_session startRunning];
    
    _off = 1;
//    _lineTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(moveLine) userInfo:nil repeats:YES];
   
}

- (void)moveLine{
    
    _off +=1 ;
    [_lineLabel setTransform:CGAffineTransformMakeTranslation(0, _off)];
    if (_off >= _qrView.frame.size.height - 3) {
        _off = 1;
    }
}
- (void)dealloc{
    [_lineTimer invalidate];
    [_session stopRunning];
    _lineTimer = nil;
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_session stopRunning];
    [_lineTimer invalidate];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
    }];
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus != AVAuthorizationStatusAuthorized){
        return;
    }
    [_session startRunning];
    _lineTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(moveLine) userInfo:nil repeats:YES];;
}

//扫描成功之后的代理
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    if (metadataObjects.count > 0) {
        NSString *stringValue;//扫描结果
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        stringValue = metadataObject. stringValue ;
        [self capStop:stringValue];
         [_session stopRunning];
    }else{
        [SCTool showMessage:@"暂未识别此二维码"];
    }
}
- (void)capStop:(NSString *)code{
    [SCTool showMessage:@"扫描成功,正在处理..."];
    DLog(@"%@",code);
    
    __weak __typeof(&*self)weakSelf = self;
    
    NSRange ran = [code rangeOfString:@"scanauthcode"];
    if (ran.location != NSNotFound) {
    
        SCUser *user = [SCUserTool loadInfo];
        if (![user.joinin_state isEqualToString:@"0"]) {
            
            [SCTool showError:@"您不能进行扫描"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            return;
        }
        
        [SCApiTool ScSscanauthcode:code success:^(NSString *msg) {
            
            [SCTool showSuccess:msg];
            
            for (UIViewController *temp in self.jt_navigationController.jt_viewControllers) {
                if ([temp isKindOfClass:[SCLoginController class]]) {
                    [weakSelf updateToken];
                    return ;
                }
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
            
        } failure:^(NSString *errormsg) {
            
            [SCTool showError:errormsg];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        }];
        return;
    }
     NSRange ranCode = [code rangeOfString:@"scanordercode"];
    if (ranCode.location != NSNotFound) {
        [SCApiTool ScScanUrl:code success:^(NSDictionary *dic) {
            [SCTool showSuccess:@"核销完毕"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                VerResultController *resultVC = [[VerResultController alloc] init];
                resultVC.listCode = 1;
                resultVC.listDic = dic;
                [weakSelf.navigationController pushViewController:resultVC animated:YES];
            });
        } failure:^(NSString *errormsg) {
            [SCTool showError:errormsg];
        }];
        return;
    }
    [SCTool showMessage:@"请扫描正确二维码"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    });
}

- (void)updateToken{

    [SCApiTool ScRefreshSuccess:^(NSArray *data) {
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIApplication sharedApplication].keyWindow.rootViewController =[[JTNavigationController alloc] initWithRootViewController:[[HomeController alloc] init]];
//        });
        
    } failure:^(NSString *errormsg) {
        
    }];
    
    
    
}



- (void)openOrClose:(UIButton *)sender{
    sender.selected = !sender.selected;
    if ([sender isSelected]) {
        [_device lockForConfiguration:nil];
        [_device setTorchMode:AVCaptureTorchModeOn];
        [_device unlockForConfiguration];
    }else{
        [_device lockForConfiguration:nil];
        [_device setTorchMode:AVCaptureTorchModeOff];
        [_device unlockForConfiguration];
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
